<template>
  <div class="container">
    <div class="userInfo">
      <img :src="userInfo.avatarUrl" alt="">
    </div>

    <!-- 组件：已经过去多少天了 -->
    <YearProgress></YearProgress>

    <button v-if="userInfo.openId" @click="scanBook" class="btn">添加图书</button>
    <button v-else open-type="getUserInfo" lang="zh_CN" class='btn' @getuserinfo="login">{{userInfo.nickName}}</button>
  </div>
</template>
<script>
  import qcloud from 'wafer2-client-sdk'
  // 组件：已经过去多少天了
  import YearProgress from '@/components/YearProgress'
  import { showSuccess, post, showModal } from '@/util'
  import config from '@/config'
  export default {
    components: {
      YearProgress
    },
    data () {
      return {
        userInfo: {
          avatarUrl: '../../../static/img/unlogin.png',
          nickName: '点击登录'
        }
      }
    },
    methods: {
      /**
       * 添加图书
       * @param isbn 图书信息
       */
      async addBook (isbn) {
        const res = await post('/weapp/addbook', {
          isbn,
          openid: this.userInfo.openId
        })
        console.log(res)
        showModal('添加成功', `${res.title}添加成功`)
      },
      /**
       * 扫描图书
       */
      scanBook () {
        wx.scanCode({
          success: (res) => {
            if (res.result) {
              this.addBook(res.result)
            }
          }
        })
      },
      /**
       * 登录
       */
      login () {
        let user = wx.getStorageSync('userInfo')
        const self = this
        if (!user) {
          qcloud.setLoginUrl(config.loginUrl)
          /**
           * 调用登录
           */
          qcloud.login({
            success: function (userInfo) {
              /**
               * 获取用户信息
               */
              qcloud.request({
                url: config.userUrl,
                login: true,
                success (userRes) {
                  console.log('登录成功', userInfo)
                  showSuccess('登录成功')
                  wx.setStorageSync('userInfo', userRes.data.data)
                  self.userInfo = userRes.data.data
                }
              })
            },
            fail: function (err) {
              showSuccess('登录失败')
              console.log('登录失败', err)
            }
          })
        }
      }
    },
    /**
     * 自动执行函数
     */
    onShow () {
      let userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    }
  }
</script>
<style lang="scss" type="text/scss">
  .container {
    padding: 0 30rpx;
    .userInfo {
      margin-top: 100rpx;
      text-align: center;
      .btn-login {

      }
      img {
        width: 150rpx;
        height: 150rpx;
        margin: 20rpx;
        border-radius: 50%;
      }
    }
  }
</style>
